package com.lu.dog.view;

import android.content.Context;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;
import android.view.View;
import android.webkit.WebView;

/**
 * @author Yue
 * @date 2017/12/25 21:11
 */

public class DogWebView extends WebView {
    private OnScrollChangeListener mOnScrollChangeListener;
    /**
     * Runnable延迟执行的时间
     */
    private long delayMillis = 1000;

    /**
     * 上次滑动的时间
     */
    private long lastScrollUpdate = -1;


    private Runnable scrollerTask = new Runnable() {
        @Override
        public void run() {
            if (mOnScrollChangeListener != null) {
                long currentTime = System.currentTimeMillis();
                if ((currentTime - lastScrollUpdate) >= 1000) {
                    lastScrollUpdate = -1;
                    mOnScrollChangeListener.onScrollEnd(DogWebView.this, pointlHold.l,pointlHold.t,pointlHold.oldl,pointlHold.oldt);
                } else {
                    postDelayed(this, delayMillis);
                }
            }
        }
    };

    public DogWebView(Context context) {
        super(context);
    }

    public DogWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public DogWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public DogWebView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    public DogWebView(Context context, AttributeSet attrs, int defStyleAttr, boolean privateBrowsing) {
        super(context, attrs, defStyleAttr, privateBrowsing);
    }

    private class PointlHold{
        int l;
        int t;
        int oldl;
        int oldt;
    }
    private PointlHold pointlHold = new PointlHold();
    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);

        if (mOnScrollChangeListener != null) {
            if (lastScrollUpdate == -1) {
                // 更新ScrollView的滑动时间
                lastScrollUpdate = System.currentTimeMillis();
                mOnScrollChangeListener.onScrollStart(this, l, t, oldl, oldt);
                postDelayed(scrollerTask, delayMillis);
            }
        }
        pointlHold.l = l;
        pointlHold.t = t;
        pointlHold.oldl = oldl;
        pointlHold.oldt = oldt;
    }

    public void setOnScrollChangeListener(OnScrollChangeListener onScrollChangeListener) {
        mOnScrollChangeListener = onScrollChangeListener;
    }

    public interface OnScrollChangeListener {

        /**
         * 滑动开始
         */
        void onScrollStart(View v, int l, int t, int oldl, int oldt);

        /**
         * 滑动结束
         */
        void onScrollEnd(View v, int l, int t, int oldl, int oldt);
    }
}
